package com.hhh.springai_test.tasks;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hhh.springai_test.config.AppConfig;
import com.hhh.springai_test.exception.BusinessException;
import com.hhh.springai_test.model.po.ReadingRoom;
import com.hhh.springai_test.model.po.ReadingRoomReservation;
import com.hhh.springai_test.model.po.User;
import com.hhh.springai_test.service.ReadingRoomReservationService;
import com.hhh.springai_test.service.ReadingRoomService;
import com.hhh.springai_test.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class ReadingRoomTask {

    @Resource
    private ReadingRoomReservationService readingRoomReservationService;

    @Resource
    private ReadingRoomService readingRoomService;

    @Resource
    private AppConfig appConfig;

    @Resource
    private JavaMailSender javaMailSender;

    @Resource
    private UserService userService;

    @Scheduled(cron = "0 * * * * ?")
    @Transactional(rollbackFor = Exception.class)
    public void updateReadingRoomReservationStatus() {
        // 获取当前时间
        Date now = new Date();

        // 查询所有状态为1的预约记录
        List<ReadingRoomReservation> reservations = readingRoomReservationService.listReadingRoomReservation();

        // 遍历预约记录，更新状态
        for (ReadingRoomReservation reservation : reservations) {
            Date startTime = reservation.getStarttime();
            Date endTime = reservation.getEndtime();
            Integer seatnumber = reservation.getSeatnumber();
            Long userid = reservation.getUserid();
            User user = userService.getById(userid);
            String email = user.getEmail();
            // 如果当前时间超过预约结束时间，删除该预约记录
            if (now.after(endTime)) {
                readingRoomReservationService.removeById(reservation.getId());
                Long roomid = reservation.getRoomid();
                ReadingRoom readingRoom = readingRoomService.getById(roomid);
                Integer currentcount = readingRoom.getCurrentcount();
                String seatstatus = readingRoom.getSeatstatus();
                
                // 更新当前座位数
                readingRoom.setCurrentcount(currentcount - 1);
                
                // 更新座位状态
                JSONArray seatArray = JSON.parseArray(seatstatus);
                
                // 查找并更新对应座位的状态
                for (int i = 0; i < seatArray.size(); i++) {
                    JSONObject seat = seatArray.getJSONObject(i);
                    if (seat.getInteger("number").equals(seatnumber)) {
                        seat.put("status", 1);  // 将状态从0改为1
                        break;
                    }
                }
                // 更新回数据库
                readingRoom.setSeatstatus(seatArray.toJSONString());
                // 格式化结束时间
                java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                String formattedEndTime = sdf.format(endTime);

                String emailContent = "<div style=\"background-color: #f0f0f0; padding: 20px; font-family: Arial, sans-serif;\">\n" +
                        "    <h1 style=\"color: #800000; text-align: center; font-size: 24px;\">星轨图书借阅系统提醒</h1>\n" +
                        "    <div style=\"background-color: white; padding: 20px; border-radius: 10px; margin: 20px;\">\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">亲爱的 <strong>" + user.getNickName() + "</strong>：</p>\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">您的阅览室预约已过期，详细信息如下：</p>\n" +
                        "        <ul style=\"color: #800000; font-size: 16px; line-height: 1.6;\">\n" +
                        "            <li>预约阅览室：<strong>" + readingRoom.getRoomname() + "</strong></li>\n" +
                        "            <li>座位号：<strong>" + seatnumber + "号</strong></li>\n" +
                        "            <li>过期时间：<strong>" + formattedEndTime + "</strong></li>\n" +
                        "        </ul>\n" +
                        "        <p style=\"color: #800000; font-size: 16px; line-height: 1.6;\">如需重新预约，请访问 <a href=\"https://www.example.com\" style=\"color: #800000; text-decoration: none;\">星轨-图书借阅系统</a> 安排新的时间。</p>\n" +
                        "    </div>\n" +
                        "    <p style=\"color: #800000; font-size: 16px; line-height: 1.6; text-align: center;\">感谢您的理解与支持！</p>\n" +
                        "    <div style=\"text-align: center; margin-top: 20px;\">\n" +
                        "        <a href=\"http://localhost:5173/reading-room\" style=\"background-color: #800000; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; font-size: 16px;\">立即重新预约</a>\n" +
                        "    </div>\n" +
                        "</div>";
                sendEmailCode(email, emailContent);
                readingRoomService.updateById(readingRoom);
            }
        }
    }

    public void sendEmailCode(String toEmail, String value) {
        try {
            // 创建MimeMessage实例
            jakarta.mail.internet.MimeMessage message = javaMailSender.createMimeMessage();
            // 使用MimeMessageHelper来设置邮件的各个部分，true表示支持多部分和HTML
            MimeMessageHelper helper = new MimeMessageHelper(message, true, "UTF-8");
            // 设置发件人邮箱地址
            helper.setFrom(appConfig.getSendUsername());
            // 设置收件人邮箱地址
            helper.setTo(toEmail);
            // 设置邮件主题
            helper.setSubject("星轨-图书借阅系统");
            // 设置邮件正文内容，第二个参数true表示这是HTML内容
            helper.setText(value, true);
            // 设置邮件发送日期
            helper.setSentDate(new Date());
            // 发送邮件
            javaMailSender.send(message);
        } catch (jakarta.mail.MessagingException e) {
            log.error("邮件发送失败", e);
            throw new BusinessException(407, "邮件发送失败");
        }
    }
}
